package com.jinyi.wwdeng.autodialer.manager

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.TELECOM_SERVICE
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.telecom.TelecomManager
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.jinyi.wwdeng.autodialer.data.CallTask
import com.jinyi.wwdeng.autodialer.data.CallTaskEntity

/**
 * 拨号管理
 */
class DialerManager private constructor(context: Context) {

    private val context: Context = context.applicationContext

    private var telecomManager: TelecomManager? = null

    // 执行拨号操作（需要在主线程调用）
    fun dialNumber(phoneNumber: CallTask): Boolean {
        return try {
            val intent = Intent(Intent.ACTION_CALL).apply {
                data = "tel:${phoneNumber.phoneNumber}".toUri()
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            Log.e("DialerManager", "拨号失败: ${e.message}")
            false
        }
    }

    // 执行拨号操作
    fun dialNumberV2(phoneNumber: CallTask): Boolean {
        if (telecomManager == null){
            telecomManager = context.getSystemService(TELECOM_SERVICE) as TelecomManager
        }
        return try {
            val uri = Uri.fromParts("tel", phoneNumber.phoneNumber, null)
            telecomManager?.placeCall(uri, null)
            true
        } catch (e: SecurityException){
            Log.e("DialerManager","拨号失败: 缺少权限 -> ${e.message}")
            false
        }
    }

    //挂断
    fun endCall(){
        if (telecomManager == null){
            telecomManager = context.getSystemService(TELECOM_SERVICE) as TelecomManager
        }
        try {
            telecomManager?.let { telecomManager ->
                if (telecomManager.isInCall){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        telecomManager.endCall()
                    }
                }
            }
        } catch (e: SecurityException){
            Log.e("DialerManager","挂断失败: 缺少权限 -> ${e.message}")
            false
        }
    }

    // 检查通话权限
    fun hasCallPermission(): Boolean {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED
    }

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var INSTANCE: DialerManager? = null
        fun getInstance(context: Context): DialerManager {
            return INSTANCE ?: synchronized(this) {
                val instance = DialerManager(context.applicationContext)
                INSTANCE = instance
                instance
            }
        }
    }
}